<?php
namespace Process;
use Process\Share;
use Process\Base;
use Exception ;

class C extends Base
{
    public $process_index ;
    /**
     * 是否接收到了停止信号 1接收到了停止信号，0 没有
     * @var
     */
    protected $stop_signal ;

    protected $memory_limit ;

    protected $share ;

    public function __construct($process_title , $process_index,$run_tmp_path,$memory_limit=600)
    {
        parent::__construct();
        $this->pid = getmypid() ;
        $this->process_identity = 'work';
        $this->memory_limit = $memory_limit;
        $this->process_title = $process_title;
        $this->process_index = $process_index;
        cli_set_process_title("{$this->process_title} : {$this->process_identity}[{$this->process_index}]");
        $this->registerSignal();
    }


    public function run($callBack,array $param_arr)
    {
        do{
            try{
                call_user_func_array($callBack, $param_arr);
                if($this->stop_signal)
                {
                    $error_string = 'process stop by signal!';
                    goto end ;
                }
                if(memory_get_usage()/1024/1024 >$this->memory_limit)
                {
                    $error_string = 'process stop by memory limit!';
                    goto end ;
                }
            }
            catch(Exception $e)
            {
                $this->log($this->error($e, __METHOD__));
            }
        }
        while(true);
        $error_string = 'process stop by unknow error!';
        end:
        $this->log($error_string);
        exit;
    }

    /**
     * @return bool
     */
    protected function registerSignal()
    {
        return
            pcntl_signal(SIGUSR2, array($this, 'signalHandle')) &&
            pcntl_signal(SIGUSR1, array($this, 'signalHandle')) &&
            pcntl_signal(SIGINT, array($this, 'signalHandle')) &&
            pcntl_signal(SIGTERM, array($this, 'signalHandle')) &&
            pcntl_signal(SIGHUP, array($this, 'signalHandle'));
    }

    public function signalHandle($signal)
    {
        switch ($signal)
        {
            case SIGTERM :
            case SIGINT:
                // 退出信号
                $this->stop_signal = 1;
                return;
            case SIGCHLD:
                //TODO 子进程退出信号处理
                return  ;
            case SIGHUP://检测是进程是否hang住，如果能正常回应代表没有hang住
                if(empty($this->share))
                {
                    $this->share  = new Share($path);
                }
                return ;
            case SIGUSR1:
            case SIGUSR2:
            default:
                //其他信号处理
        }
    }

    /**
     * 增强sleep 可以小数
     * @param $sleep
     */
    public function sleep($sleep)
    {
        usleep($sleep*1000000);
    }

    public function __destruct()
    {
        // TODO: Implement __destruct() method.
    }
}